<!--设备标签详情-->
<template>
  <div class="equipment-labels-details">
    <el-form :inline="true" class="search-form">
      <div class="header">
        <span class="back" @click="goBack"><i class="iconfont icon-fanhui" style="font-size: 24px;"></i></span>
        <span class="label-name">{{ deviceTagDetailData.tagName || '-' }}</span>
        <span class="equipment-num">设备数量：{{ deviceTagDetailData.amount }}</span>
      </div>
      <el-form-item>
        <el-input v-model="deviceUuid" placeholder="请输入设备标识" clearable @keyup.enter.native="getList('search', 'deviceUuid')">
          <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="getList('search', 'deviceUuid')"></el-button>
        </el-input>
      </el-form-item>
      <el-button type="primary" size="14" @click="handleGenerate">导入设备</el-button>
    </el-form>
    <div class="label-desc">标签说明：{{ deviceTagDetailData.tagDescription || '-'}}</div>
    <el-button :type="multipleSelection.length ? 'danger' : 'primary'" size="14" :disabled="!multipleSelection.length" class="all-delete" @click="handleDelete('all')">删除</el-button>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="设备标识">
        <template slot-scope="scope">
          {{ scope.row.deviceUuid || "-" }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="operate"
            @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog
      title="上传设备标识"
      :visible.sync="dialogVisible"
      width="596px"
      :before-close="handleClose"
      custom-class="white-list-dialog">
      <el-form
        ref="form"
        :model="formInfo"
        :rules="rules"
        width="596px"
        label-width="80px"
        label-position="right">
        <el-form-item label="文件导入" prop="file">
          <el-upload
            class="upload-demo"
            action="/ota/v1/device/tag/detail/import-device-tag"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            multiple
            :accept="uploadFileType">
            <el-button v-if="!uploadSuccessedFile" size="small" icon="el-icon-plus" class="upload-btn">上传文件</el-button>
            <el-input v-else v-model="formInfo.fileName" class="file-name">{{ formInfo.fileName }}</el-input>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button size="small" class="download-btn" @click="handleDownload">
            <span class="text">模版文件下载</span>
            <span>设备标识.csv</span>
          </el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import store from '@/store'
import { getDetailsList, deleteLabelsDetails, template, saveFile, deviceTagDetail } from '@/api/device-identity-auth/equipment-labels'
export default {
  name: 'tripletDetails',
  data() {
    return {
      headers: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token,
        id: this.id
      },
      tableData: [], // 列表数据
      deviceTagDetailData: {}, // 设备标签详情
      multipleSelection: [], // 表格选中数据
      deviceUuid: '', // 设备标识
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: true,
      dialogVisible: false,
      uploadSuccessedFile: false,
      fileList: [], // 上传的固件文件
      uploadSuccessOrError: false, // 上传固件成功则展示固件基本信息否则不展示
      uploadFileType: 'csv', // 文件类型
      rules: {
        file: { required: true, validator: this.validateFile, trigger: 'blur' }
      },
      id: '', // 标签id
      tagName: '', // 标签名称
      formInfo: {
        fileName: '', // 上传成功的csv文件名称
        fileUrl: '' // 上传成功的csv文件URL
      }
    }
  },
  created() {
    this.id = this.$route.query.id
    // this.tagName = this.$route.query.tagName
    this.getDeviceTagDetail()
    this.getList()
  },
  methods: {
    // 上传白名单校验
    validateFile(rule, value, callback) {
      if (this.fileList.length === 0) {
        callback(new Error('请上传文件'))
      } else {
        callback()
      }
    },
    /**
     * 详情列表
     */
    getList() {
      const params = {
        deviceTagId: this.id,
        deviceUuid: this.deviceUuid,
        size: this.pageSize,
        current: this.currentPage
      }
      getDetailsList(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 设备标签详情数据
     */
     getDeviceTagDetail() {
      this.loading = true
      const params = {
        deviceTagId: this.id
      }
      deviceTagDetail(params).then(res => {
        this.deviceTagDetailData = res.data.data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 返回
    goBack() {
      this.$router.push({
        path: '/device-identity-auth/equipment-labels/index'
      })
    },
    // 设备标识csv模板下载
    handleDownload() {
      template().then(res => {
        this.downBlobFile(res.data.data, {}, '设备标识')
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 导入设备标签
    handleGenerate() {
      this.dialogVisible = true
    },
    // 保存上传的设备标识文件
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            fileUrl: this.formInfo.fileUrl,
            deviceTagId: this.id
          }
          saveFile(params).then(res => {
            this.dialogVisible = false
            this.$refs['form'].resetFields()
            this.uploadSuccessedFile = false
            this.formInfo.fileName = ''
            this.formInfo.fileUrl = ''
            this.$message.success('导入成功')
            this.getDeviceTagDetail()
            this.getList()
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    },
    // 关闭导入设备弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
      this.uploadSuccessedFile = false
      this.formInfo.fileName = ''
      this.formInfo.fileUrl = ''
      this.fileList = []
    },
    // 表格选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id)
    },
    // 列表单个删除
    handleDelete(id) {
      const params = {
        deviceTagDetailIdList: id === 'all' ? this.multipleSelection : [id]
      }
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLabelsDetails(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getDeviceTagDetail()
          this.getList()
        }).catch(err => {
          this.$message.error(err.message)
        })
      }).catch(err => {})
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    // 上传之前做校验
    beforeUpload(file) {
      // 在上传之前检查文件类型
      const extension = file.name.split('.').pop() // 获取上传文件的扩展名
      const allowedExtensions = this.uploadFileType

      if (!allowedExtensions.includes(extension)) {
        this.$message.error('请使用正确的模板')
        return false // 阻止文件上传
      }

      return true // 允许文件上传
    },
    // 文件上传成功
    uploadSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.fileList = file
        this.formInfo.fileName = res.data.fileName
        this.formInfo.fileUrl = res.data.fileUrl
        this.uploadSuccessedFile = true
      } else {
        this.$message.error(res.msg)
      }
    },
    // 文件上传失败
    uploadError(err, file, fileList) {
      this.$message.error(err)
    }
  }
}
</script>
<style lang="scss" scoped>
.equipment-labels-details {
  .search-form {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .header {
      display: flex;
      align-items: center;
    }

    .el-form-item,
    .el-form-item--small.el-form-item {
      margin-bottom: 0px;
    }

    .back {
      cursor: pointer;
      margin-right: 8px;
    }

    .label-name {
      font-weight: 400;
      color: #252525;
      font-size: 18px;
      margin-right: 24px;
    }
    .equipment-num {
      font-weight: 400;
      color: #252525;
      font-size: 16px;
      margin-right: 24px;
    }
  }

  .label-desc {
    margin-bottom: 12px;
    margin-left: 32px;
    font-size: 16px;
    font-weight: 400;
    color: #252525;
  }

  .all-delete {
    width: 90px;
    margin-bottom: 18px;
  }

  .download-btn {
    background: rgba(39,95,232,0.1);
    border-radius: 4px;
    border: 1px solid #DEDEDE;
    width: 100%;
    height: 32px;
    font-weight: 400;
    color: #275FE8;
    margin-top: 8px;
    font-size: 14px;

    .text {
      margin-right: 24px;
    }
  }
}

::v-deep .upload-demo {
  .el-upload {
    width: 100%;
  }
  .upload-btn,
  .file-name {
    width: 100%;
    color: #275FE8;
    font-size: 14px;
    height: 32px;

    ::v-deep .el-input__inner {
      color: #275FE8;
    }
  }

  .el-upload-list {
    display: none;
  }

  .el-button {
    width: 100%;
    color: #275fe8;
  }
}
</style>
